package com.ha8.netease.views.components
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	
	[Event(name="complete", type="flash.events.Event")]
	
	/**
	 * Reference Image
	 * 
	 * @author rogo
	 */	
	public class ReferImage extends CornerImage
	{
		public function ReferImage()
		{
			super();
		}
		
		//--------------------------------------------------------------------------
		//
		//  Variables
		//
		//--------------------------------------------------------------------------
		
		private var imageStream:URLStream;
		
		//--------------------------------------------------------------------------
		//
		//  Overridden Methods
		//
		//--------------------------------------------------------------------------
		
		override public function set source(value:Object):void
		{
			if (!(value is String))
				return;
			
			imageStream = new URLStream();
			imageStream.addEventListener(Event.COMPLETE, completeHandler);
			imageStream.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			
			var urlReq:URLRequest = new URLRequest(value.toString());
			var urlReqHeader:URLRequestHeader = new URLRequestHeader('Referer', 'http://open.t.163.com');
			urlReq.requestHeaders.push(urlReqHeader);
			
			imageStream.load(urlReq);
		}
		
		override protected function loadComplete(event:Event):void
		{
			super.loadComplete(event);
			dispatchEvent(event);
		}
		
		//--------------------------------------------------------------------------
		//
		//  Event Handlers
		//
		//--------------------------------------------------------------------------
		
		private function completeHandler(e:Event):void
		{
			var ba:ByteArray = new ByteArray();
			imageStream.readBytes(ba);
			super.source = ba;
		}
		
		private function errorHandler(e:Event):void
		{}
		
	}
}